package com.fuze.service.impl;

import cn.hutool.core.util.IdUtil;
import com.fuze.common.Advice;
import com.fuze.common.CustomException;
import com.fuze.domain.dto.DataGridView;
import com.fuze.service.UploadService;
import com.fuze.utils.CheckFileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.stream.Stream;

/**
 * @author sepc_
 * @date 4/20/2021 15:02
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${com.fuze.upload-path}")
    String path;

    @Override
    public DataGridView upload(MultipartFile[] fileList) {
        ArrayList<String> list = new ArrayList<>();
        Stream.of(fileList)
                .forEach(image -> {
                    String suffix = CheckFileUtils.getSuffix(image)
                            .orElseThrow(() -> new CustomException(Advice.FAILED_IMAGE_UPLOAD));
                    File folder = new File(path);
                    if (!folder.exists()) {
                        boolean mkdirs = folder.mkdirs();
                        if (!mkdirs) {
                            throw new CustomException(Advice.FAILED_IMAGE_UPLOAD);
                        }
                    }
                    // TODO: 4/20/2021 需要注意的是，文件名使用的是随机字符串，如果需要和用户关联起来的话，需要额外的处理
                    String fullName = path + IdUtil.simpleUUID() + suffix;
                    File dest = new File(fullName);
                    if (dest.exists()) {
                        throw new CustomException(Advice.FAILED_IMAGE_UPLOAD);
                    }
                    try {
                        image.transferTo(dest);
                        list.add(fullName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
        return new DataGridView((long) list.size(), list);
    }
}
